"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

import scanning
from templatetag import NodeList as NodeList
from templatetag import TextNode as TextNode
from templatetag import VarNode as VarNode
from templatetag import TranslateNode as TranslateNode
from templatetag import registered_tags as registered_tags
#
class TemplateSyntaxError(Exception):
        pass
                
#parse 
class Parse:
        def __init__(self, token_list ):
                self.token_list = token_list
                
        def next_token( self ):
                return self.token_list.pop( 0 )
        
        def back_token( self , token ):
                self.token_list.insert( 0, token )
                
        def process( self , until_tag = [] ):
                node_list = NodeList()
                while self.token_list:
                        token = self.next_token( )
                        if token.type == scanning.TOKEN_TEXT:
                                node_list.append( TextNode( token.value ) )
                        elif token.type == scanning.TOKEN_VAR:
                                node_list.append( VarNode( token.value ) )
                        elif token.type == scanning.TOKEN_TRANSLATE:
                                node_list.append( TranslateNode( token.value ) )
                        elif token.type == scanning.TOKEN_BLOCK:
                                if token.value.strip() in until_tag:
                                        self.back_token( token )
                                        return node_list
                                operation = token.value.strip().split()[0]
                                node = registered_tags[ operation ]( self, token )
                                node_list.append( node )
                        else:
                                raise TemplateSyntaxError, "Unsupport tag_type(s): '%d'" %  token.type
                if until_tag:
                        raise TemplateSyntaxError, "Unclosed tag(s): '%s'" % ', '.join(until_tag)
                return node_list
